<template>
  <div class="chat-container" :class="{ dark: isDarkMode }">
    <!-- 顶部导航栏 -->
    <header class="chat-header">
      <div class="header-content">
        <h1>🎭 七牛云 AI 角色扮演</h1>
        <div class="header-controls">
          <button
              @click="toggleDarkMode"
              class="theme-toggle"
              aria-label="切换主题模式"
              :title="isDarkMode ? '切换至浅色模式' : '切换至深色模式'"
          >
            {{ isDarkMode ? '🌞' : '🌙' }}
          </button>
          <button
              @click="showConversations = !showConversations"
              class="conv-toggle"
              aria-label="查看会话列表"
              :title="showConversations ? '隐藏会话列表' : '显示会话列表'"
          >
            💬
            <span v-if="unreadCount > 0" class="unread-badge">{{ unreadCount }}</span>
          </button>
        </div>
      </div>
    </header>

    <main class="chat-main">
      <!-- 会话列表侧边栏 -->
      <aside class="conversations-sidebar" :class="{ active: showConversations }">
        <div class="sidebar-header">
          <h2>会话列表</h2>
          <button @click="newConversation" class="new-conv-btn" title="创建新会话">+ 新会话</button>
        </div>
        <div class="conversations-list">
          <!-- 空会话提示 -->
          <div class="empty-conv" v-if="conversations.length === 0">
            <p>暂无会话记录</p>
            <p>点击"新会话"开始聊天吧~</p>
          </div>

          <div
              v-for="conv in conversations"
              :key="conv.id"
              :class="['conv-item', { active: currentConversationId === conv.id, unread: conv.unread }]"
              @click="switchConversation(conv.id, conv.role)"
              :title="`与${conv.role}的会话`"
          >
            <div class="conv-role">
              {{ getRoleAvatar(conv.role) }} {{ conv.role }}
            </div>
            <div class="conv-preview">{{ conv.lastMessage || '新会话' }}</div>
            <div class="conv-meta">
              <span class="conv-time">{{ formatConvTime(conv.updateTime) }}</span>
              <span v-if="conv.unread" class="conv-unread">●</span>
            </div>
            <button
                @click.stop="deleteConversation(conv.id)"
                class="delete-conv"
                aria-label="删除会话"
                title="删除会话"
            >
              ×
            </button>
          </div>
        </div>
      </aside>

      <!-- 主聊天区域 -->
      <div class="chat-area">
        <!-- 角色选择 -->
        <div class="role-section">
          <label>当前角色：</label>
          <select
              v-model="selectedRole"
              class="role-select"
              @change="handleRoleChange"
              aria-label="选择AI角色"
          >
            <option value="哈利波特">🧙‍♂️ 哈利波特</option>
            <option value="苏格拉底">🏛️ 苏格拉底</option>
            <option value="福尔摩斯">🔍 福尔摩斯</option>
            <option value="爱因斯坦">⚛️ 爱因斯坦</option>
          </select>

          <div class="chat-actions">
            <button
                @click="downloadChatHistory"
                class="action-btn"
                :disabled="messages.length === 0"
                title="导出聊天记录"
            >
              📥 导出
            </button>
            <button
                @click="clearMessages"
                class="action-btn clear-btn"
                :disabled="messages.length === 0"
                title="清除当前对话"
            >
              🗑️ 清除
            </button>
          </div>
        </div>

        <!-- 聊天消息区域 -->
        <div class="messages-container" ref="messagesContainer">
          <!-- 空状态提示 -->
          <div class="empty-state" v-if="messages.length === 0 && !loading">
            <div class="empty-icon">💬</div>
            <p>开始与 {{ selectedRole }} 对话吧</p>
            <div class="role-desc">{{ getRoleDescription() }}</div>
          </div>

          <!-- 消息列表 -->
          <div
              v-for="(msg, index) in messages"
              :key="msg.id"
              :class="['message', msg.sender]"
          :data-id="msg.id"
          >
          <div class="message-avatar">
            {{ msg.sender === 'ai' ? getRoleAvatar() : '👤' }}
          </div>
          <div class="message-content">
            <div class="message-sender">{{ msg.sender === 'ai' ? selectedRole : '我' }}</div>
            <div class="message-text">{{ msg.content }}</div>
            <div class="message-meta">
              <span class="message-time">{{ formatTime(msg.timestamp) }}</span>
              <div class="message-actions">
                <button
                    @click="copyMessage(msg.content, index)"
                    class="copy-btn"
                    aria-label="复制消息"
                    title="复制消息"
                >
                  {{ copiedIndex === index ? '✓ 已复制' : '📋' }}
                </button>
                <button
                    @click="deleteMessage(index)"
                    class="delete-btn"
                    aria-label="删除消息"
                    title="删除消息"
                    v-if="msg.sender === 'user'"
                >
                  🗑️
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading">
          <div class="typing-dots">
            <span></span><span></span><span></span>
          </div>
          <p class="typing-text">{{ selectedRole }}正在思考中...</p>
        </div>

        <!-- 错误重试 -->
        <div v-if="showRetry" class="retry-section">
          <p>发送失败，请重试</p>
          <button @click="retrySend" class="retry-btn">重试</button>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-section">
        <div class="input-toolbar">
          <button
              @click="openEmojiPicker"
              class="toolbar-btn"
              aria-label="添加表情"
              title="表情"
          >
            😊
          </button>
          <button
              @click="insertEmoji('👍')"
              class="toolbar-btn"
              title="点赞"
          >
            👍
          </button>
          <button
              @click="insertEmoji('❓')"
              class="toolbar-btn"
              title="疑问"
          >
            ❓
          </button>
          <span class="input-counter">{{ inputLength }}/500</span>
        </div>

        <!-- 表情选择器 (默认隐藏) -->
        <div class="emoji-picker" v-if="showEmojiPicker">
          <div class="emoji-grid">
            <span v-for="emoji in commonEmojis" :key="emoji" @click="insertEmoji(emoji)">{{ emoji }}</span>
          </div>
        </div>

        <div class="input-group">
            <textarea
                v-model="inputMessage"
                @keyup.enter.exact="sendMessage"
                @keyup.enter.shift="handleShiftEnter"
                @input="handleInputChange"
                placeholder="输入您想说的话... (Shift+Enter换行，最多500字)"
                :disabled="loading || inputLength >= 500"
                class="message-input"
                rows="1"
                ref="messageInput"
                aria-label="输入消息"
            ></textarea>
          <button
              @click="sendMessage"
              :disabled="!inputMessage.trim() || loading || inputLength >= 500"
              class="send-btn"
              aria-label="发送消息"
              title="发送消息 (Enter)"
          >
            {{ loading ? '发送中...' : '发送' }}
          </button>
        </div>
      </div>
  </div>
  </main>

  <footer class="chat-footer">
    <div :class="['status', status.type]">
      <span class="status-icon">{{ getStatusIcon() }}</span>
      {{ status.message }}
      <button
          v-if="status.type === 'error'"
          @click="retryConnection"
          class="retry-link"
      >
        重试
      </button>
    </div>
  </footer>

  <!-- 通知提示 -->
  <div
      class="notification"
      :class="{ show: showNotification, success: notificationType === 'success', error: notificationType === 'error' }"
      @click="showNotification = false"
      role="alert"
  >
    {{ notificationMessage }}
  </div>
  </div>
</template>

<script>
import axios from 'axios';
import { v4 as uuidv4 } from 'uuid'; // 引入uuid生成唯一ID

export default {
  name: 'ChatView',
  data() {
    return {
      // 核心状态
      selectedRole: '哈利波特',
      inputMessage: '',
      messages: [],
      loading: false,
      currentConversationId: null,
      lastFailedMessage: null, // 记录失败的消息用于重试
      showRetry: false,

      // UI状态
      showConversations: false,
      conversations: [],
      isDarkMode: false,
      copiedIndex: -1,
      showNotification: false,
      notificationMessage: '',
      notificationType: 'success',
      showEmojiPicker: false,
      inputLength: 0, // 输入字数统计

      // 系统状态
      status: {
        type: 'success',
        message: '系统就绪'
      },

      // 常量数据
      commonEmojis: ['😊', '😂', '👍', '❤️', '疑问', '👏', '惊讶', '难过', '生气', '再见'],
      roleDescriptions: {
        '哈利波特': '来自霍格沃茨的巫师，擅长黑魔法防御术，勇敢且富有正义感',
        '苏格拉底': '古希腊哲学家，擅长通过提问引导思考，追求真理与美德',
        '福尔摩斯': '著名侦探，观察力敏锐，逻辑推理能力极强，善于破解复杂案件',
        '爱因斯坦': '物理学家，相对论创立者，对宇宙和科学有深刻见解'
      }
    };
  },
  computed: {
    // 未读会话数量
    unreadCount() {
      return this.conversations.filter(conv => conv.unread).length;
    }
  },
  mounted() {
    // 初始化
    this.checkConnection();
    this.loadConversations();
    this.checkDarkModePreference();
    this.setupAutoResize();

    // 监听窗口大小变化，重新调整布局
    window.addEventListener('resize', this.handleResize);

    // 页面离开时保存草稿
    window.addEventListener('beforeunload', this.saveDraft);
    // 恢复草稿
    this.restoreDraft();
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.handleResize);
    window.removeEventListener('beforeunload', this.saveDraft);
  },
  methods: {
    // 系统相关
    async checkConnection() {
      try {
        await axios.get('http://localhost:8080/api/health');
        this.setStatus('success', '后端服务连接正常');
      } catch (error) {
        this.setStatus('error', '后端服务连接失败');
        this.showNotificationMessage('后端服务连接失败，请检查服务是否运行', 'error');
      }
    },

    async retryConnection() {
      this.setStatus('info', '正在重连...');
      await this.checkConnection();
    },

    async loadConversations() {
      try {
        const response = await axios.get('http://localhost:8080/api/conversations');
        this.conversations = response.data.map(conv => ({
          id: conv.conversationId,
          role: conv.roleName,
          lastMessage: conv.lastMessage || '',
          updateTime: conv.updateTime ? new Date(conv.updateTime) : new Date(),
          unread: conv.unread || false // 新增未读状态
        }));
      } catch (error) {
        console.error('加载会话失败:', error);
        this.showNotificationMessage('加载会话列表失败', 'error');
      }
    },

    // 会话管理
    newConversation() {
      this.currentConversationId = null;
      this.messages = [];
      this.showConversations = false;
      this.showNotificationMessage('已创建新会话', 'success');
      // 自动聚焦输入框
      this.focusInput();
    },

    async switchConversation(conversationId, role) {
      if (this.loading) return;

      this.loading = true;
      this.setStatus('info', '加载会话中...');

      try {
        this.selectedRole = role;
        this.currentConversationId = conversationId;

        // 标记会话为已读
        this.markAsRead(conversationId);

        const response = await axios.get(`http://localhost:8080/api/conversations/${conversationId}/messages`);
        this.messages = response.data.map(msg => ({
          id: uuidv4(), // 生成唯一ID
          sender: msg.sender === 'AI' ? 'ai' : 'user',
          content: msg.content,
          timestamp: new Date(msg.timestamp)
        }));

        this.showConversations = false;
        this.scrollToBottom();
        this.setStatus('success', `已切换到与 ${role} 的会话`);
      } catch (error) {
        console.error('切换会话失败:', error);
        this.setStatus('error', '加载会话失败');
        this.showNotificationMessage('加载会话失败', 'error');
      } finally {
        this.loading = false;
      }
    },

    async deleteConversation(conversationId) {
      if (!confirm('确定要删除这个会话吗？删除后不可恢复哦~')) return;

      try {
        await axios.delete('http://localhost:8080/api/conversations', {
          params: { conversationIds: [conversationId] }
        });

        // 更新会话列表
        this.conversations = this.conversations.filter(conv => conv.id !== conversationId);

        // 如果删除的是当前会话，重置聊天界面
        if (this.currentConversationId === conversationId) {
          this.currentConversationId = null;
          this.messages = [];
        }

        this.showNotificationMessage('会话已删除', 'success');
      } catch (error) {
        console.error('删除会话失败:', error);
        this.showNotificationMessage('删除会话失败', 'error');
      }
    },

    // 标记会话为已读
    markAsRead(conversationId) {
      const convIndex = this.conversations.findIndex(conv => conv.id === conversationId);
      if (convIndex !== -1 && this.conversations[convIndex].unread) {
        this.conversations[convIndex].unread = false;
        // 同步到后端
        axios.patch(`http://localhost:8080/api/conversations/${conversationId}/read`).catch(err => {
          console.error('标记已读失败:', err);
        });
      }
    },

    async handleRoleChange() {
      if (this.messages.length > 0) {
        if (confirm(`切换角色将创建新会话，当前对话将被保存。是否继续？`)) {
          this.newConversation();
        } else {
          // 恢复之前的选择
          this.$nextTick(() => {
            const previousRole = this.conversations.find(
                conv => conv.id === this.currentConversationId
            )?.role;
            if (previousRole) {
              this.selectedRole = previousRole;
            }
          });
        }
      }
    },

    // 消息处理
    async sendMessage() {
      const userMessage = this.inputMessage.trim();
      if (!userMessage || this.loading || this.inputLength >= 500) return;

      // 保存消息用于重试
      this.lastFailedMessage = userMessage;
      this.showRetry = false;

      // 清空输入框并添加用户消息
      this.inputMessage = '';
      this.inputLength = 0;
      const newMessage = {
        id: uuidv4(),
        sender: 'user',
        content: userMessage,
        timestamp: new Date()
      };
      this.messages.push(newMessage);

      this.scrollToBottom();
      this.loading = true;
      this.setStatus('info', `${this.selectedRole}正在思考...`);

      try {
        const response = await axios.post('http://localhost:8080/api/chat', {
          role: this.selectedRole,
          message: userMessage,
          conversationId: this.currentConversationId || ''
        });

        const data = response.data;

        if (data.success) {
          // 更新当前会话ID
          this.currentConversationId = data.conversationId;

          // 添加AI回复
          this.messages.push({
            id: uuidv4(),
            sender: 'ai',
            content: data.reply,
            timestamp: new Date()
          });

          // 更新会话列表
          this.loadConversations();
          this.setStatus('success', '回复接收成功');
        } else {
          throw new Error(data.error_message || '未知错误');
        }

      } catch (error) {
        console.error('发送消息失败:', error);
        // 显示重试按钮
        this.showRetry = true;
        this.setStatus('error', '发送失败');
        this.showNotificationMessage(`发送失败: ${error.message}`, 'error');
      } finally {
        this.loading = false;
        this.scrollToBottom();
      }
    },

    // 重试发送失败的消息
    retrySend() {
      if (this.lastFailedMessage) {
        this.inputMessage = this.lastFailedMessage;
        this.inputLength = this.lastFailedMessage.length;
        this.showRetry = false;
        this.sendMessage();
      }
    },

    // 删除单条用户消息
    deleteMessage(index) {
      if (this.messages[index].sender !== 'user') return;

      if (confirm('确定要删除这条消息吗？')) {
        this.messages.splice(index, 1);
        this.showNotificationMessage('消息已删除', 'success');
        // 如果是当前会话，同步到后端
        if (this.currentConversationId) {
          axios.delete(`http://localhost:8080/api/conversations/${this.currentConversationId}/messages`, {
            data: { messageIndex: index } // 假设后端支持按索引删除
          }).catch(err => {
            console.error('删除消息失败:', err);
          });
        }
      }
    },

    clearMessages() {
      if (this.messages.length === 0) return;

      if (confirm('确定要清除当前对话历史吗？')) {
        this.messages = [];
        this.showNotificationMessage('对话已清除', 'success');
        // 同步到后端
        if (this.currentConversationId) {
          axios.delete(`http://localhost:8080/api/conversations/${this.currentConversationId}/messages`)
              .catch(err => {
                console.error('清除消息失败:', err);
              });
        }
      }
    },

    // 导出聊天记录
    downloadChatHistory() {
      if (this.messages.length === 0) return;

      let content = `与${this.selectedRole}的聊天记录\n`;
      content += `导出时间: ${new Date().toLocaleString()}\n\n`;

      this.messages.forEach(msg => {
        const sender = msg.sender === 'ai' ? this.selectedRole : '我';
        content += `[${this.formatTime(msg.timestamp)}] ${sender}: ${msg.content}\n\n`;
      });

      // 创建下载链接
      const blob = new Blob([content], { type: 'text/plain' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `与${this.selectedRole}的对话_${new Date().toLocaleDateString()}.txt`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);

      this.showNotificationMessage('聊天记录已导出', 'success');
    },

    copyMessage(content, index) {
      navigator.clipboard.writeText(content).then(() => {
        this.copiedIndex = index;

        // 2秒后重置复制状态
        setTimeout(() => {
          this.copiedIndex = -1;
        }, 2000);

        this.showNotificationMessage('消息已复制', 'success');
      }).catch(err => {
        console.error('复制失败:', err);
        this.showNotificationMessage('复制失败，请手动复制', 'error');
      });
    },

    // 表情相关
    openEmojiPicker() {
      this.showEmojiPicker = !this.showEmojiPicker;
      if (this.showEmojiPicker) {
        // 点击其他区域关闭表情选择器
        document.addEventListener('click', this.closeEmojiPickerOnOutside);
      } else {
        document.removeEventListener('click', this.closeEmojiPickerOnOutside);
      }
    },

    closeEmojiPickerOnOutside(e) {
      const emojiPicker = document.querySelector('.emoji-picker');
      const toolbarBtn = document.querySelector('.toolbar-btn');
      if (emojiPicker && !emojiPicker.contains(e.target) && !toolbarBtn.contains(e.target)) {
        this.showEmojiPicker = false;
        document.removeEventListener('click', this.closeEmojiPickerOnOutside);
      }
    },

    insertEmoji(emoji) {
      this.inputMessage += emoji;
      this.inputLength = this.inputMessage.length;
      this.focusInput();
      // 自动调整高度
      this.adjustTextareaHeight();
    },

    // 输入处理
    handleShiftEnter(e) {
      e.preventDefault();
      this.inputMessage += '\n';
      this.inputLength = this.inputMessage.length;
      this.adjustTextareaHeight();
    },

    handleInputChange() {
      this.inputLength = this.inputMessage.length;
      // 限制最大长度
      if (this.inputLength > 500) {
        this.inputMessage = this.inputMessage.substring(0, 500);
        this.inputLength = 500;
      }
    },

    // UI辅助
    formatTime(timestamp) {
      return new Date(timestamp).toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    },

    formatConvTime(timestamp) {
      const date = new Date(timestamp);
      const now = new Date();
      if (date.toDateString() === now.toDateString()) {
        // 今天的消息显示时间
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
      } else {
        // 非今天的消息显示日期
        return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
      }
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer;
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    },

    setStatus(type, message) {
      this.status.type = type;
      this.status.message = message;
    },

    getStatusIcon() {
      switch (this.status.type) {
        case 'success': return '✓';
        case 'error': return '⚠️';
        case 'info': return 'ℹ️';
        default: return '';
      }
    },

    getRoleAvatar(role = this.selectedRole) {
      switch (role) {
        case '哈利波特': return '🧙‍♂️';
        case '苏格拉底': return '🏛️';
        case '福尔摩斯': return '🔍';
        case '爱因斯坦': return '⚛️';
        default: return '🤖';
      }
    },

    getRoleDescription() {
      return this.roleDescriptions[this.selectedRole] || '';
    },

    showNotificationMessage(message, type = 'success') {
      this.notificationMessage = message;
      this.notificationType = type;
      this.showNotification = true;

      // 点击通知也可以关闭
      clearTimeout(this.notificationTimer);
      this.notificationTimer = setTimeout(() => {
        this.showNotification = false;
      }, 3000);
    },

    // 主题相关
    toggleDarkMode() {
      this.isDarkMode = !this.isDarkMode;
      localStorage.setItem('darkMode', this.isDarkMode ? 'enabled' : 'disabled');
      // 添加主题切换动画
      document.documentElement.classList.add('theme-transition');
      setTimeout(() => {
        document.documentElement.classList.remove('theme-transition');
      }, 300);
    },

    checkDarkModePreference() {
      const savedMode = localStorage.getItem('darkMode');
      if (savedMode) {
        this.isDarkMode = savedMode === 'enabled';
      } else {
        // 检测系统偏好
        this.isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
      }
    },

    // 输入框高度调整
    setupAutoResize() {
      const textarea = this.$refs.messageInput;
      if (textarea) {
        // 初始调整
        this.adjustTextareaHeight();
        // 监听输入事件
        textarea.addEventListener('input', this.adjustTextareaHeight);
        // 监听窗口大小变化
        window.addEventListener('resize', this.adjustTextareaHeight);
      }
    },

    adjustTextareaHeight() {
      const textarea = this.$refs.messageInput;
      if (textarea) {
        textarea.style.height = 'auto';
        // 限制最大高度为180px（比之前更高，适应更多内容）
        textarea.style.height = Math.min(textarea.scrollHeight, 180) + 'px';
      }
    },

    // 窗口大小变化处理
    handleResize() {
      this.adjustTextareaHeight();
      if (window.innerWidth < 768) {
        this.showConversations = false; // 小屏幕自动隐藏侧边栏
      }
    },

    // 草稿保存与恢复
    saveDraft() {
      if (this.inputMessage.trim()) {
        localStorage.setItem('chatDraft', this.inputMessage);
        localStorage.setItem('draftRole', this.selectedRole);
      }
    },

    restoreDraft() {
      const draft = localStorage.getItem('chatDraft');
      const draftRole = localStorage.getItem('draftRole');
      if (draft && draftRole === this.selectedRole) {
        this.inputMessage = draft;
        this.inputLength = draft.length;
        this.adjustTextareaHeight();
        // 3秒后自动清除草稿标记
        setTimeout(() => {
          localStorage.removeItem('chatDraft');
        }, 3000);
      }
    },

    focusInput() {
      this.$refs.messageInput?.focus();
    }
  },
  watch: {
    showConversations() {
      this.scrollToBottom();
    },
    // 切换角色时清除草稿
    selectedRole() {
      localStorage.removeItem('chatDraft');
    }
  }
};
</script>

<style scoped>
/* 全局样式增强 */
.chat-container {
  max-width: 1000px;
  margin: 0 auto;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f9f9f9;
  color: #333;
  transition: background-color 0.3s, color 0.3s;
}

.chat-container.dark {
  background: #1a1a1a;
  color: #f0f0f0;
}

/* 主题切换过渡 */
.theme-transition * {
  transition: background-color 0.3s, color 0.3s, border-color 0.3s !important;
}

/* 头部样式增强 */
.chat-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 1rem 2rem;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 10;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1000px;
  margin: 0 auto;
}

.chat-header h1 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.header-controls {
  display: flex;
  gap: 0.5rem;
}

.theme-toggle, .conv-toggle {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  border-radius: 50%;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background 0.2s, transform 0.2s;
  font-size: 1.2rem;
  position: relative;
}

.theme-toggle:hover, .conv-toggle:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.05);
}

/* 未读徽章 */
.unread-badge {
  position: absolute;
  top: -2px;
  right: -2px;
  background: #dc3545;
  color: white;
  border-radius: 50%;
  width: 16px;
  height: 16px;
  font-size: 0.7rem;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 主内容区 */
.chat-main {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 会话侧边栏增强 */
.conversations-sidebar {
  width: 280px;
  background: white;
  border-right: 1px solid #e1e5e9;
  display: flex;
  flex-direction: column;
  transform: translateX(-100%);
  position: fixed;
  height: calc(100vh - 64px - 42px);
  z-index: 10;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
}

.chat-container.dark .conversations-sidebar {
  background: #2d2d2d;
  border-right: 1px solid #444;
}

.conversations-sidebar.active {
  transform: translateX(0);
  box-shadow: 2px 0 20px rgba(0, 0, 0, 0.15);
}

.sidebar-header {
  padding: 1rem;
  border-bottom: 1px solid #e1e5e9;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-container.dark .sidebar-header {
  border-bottom: 1px solid #444;
}

.sidebar-header h2 {
  margin: 0;
  font-size: 1.1rem;
  font-weight: 600;
}

.new-conv-btn {
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 0.4rem 0.8rem;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background 0.2s, transform 0.1s;
}

.new-conv-btn:hover {
  background: #0056b3;
  transform: translateY(-1px);
}

.new-conv-btn:active {
  transform: translateY(0);
}

.conversations-list {
  flex: 1;
  overflow-y: auto;
  padding: 0.5rem;
}

/* 空会话提示 */
.empty-conv {
  padding: 2rem 1rem;
  text-align: center;
  color: #999;
  font-size: 0.95rem;
  line-height: 1.6;
}

.chat-container.dark .empty-conv {
  color: #666;
}

.conv-item {
  padding: 0.8rem;
  border-radius: 8px;
  margin-bottom: 0.5rem;
  cursor: pointer;
  transition: background 0.2s, transform 0.1s;
  position: relative;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.chat-container.dark .conv-item {
  background: #3a3a3a;
}

.conv-item:hover {
  background: #e9ecef;
  transform: translateX(2px);
}

.chat-container.dark .conv-item:hover {
  background: #4a4a4a;
}

.conv-item.active {
  background: #e6f0ff;
  border-left: 3px solid #007bff;
}

.chat-container.dark .conv-item.active {
  background: #2c3e50;
}

/* 会话未读状态 */
.conv-item.unread .conv-role {
  font-weight: 700;
}

.conv-role {
  font-weight: 600;
  margin-bottom: 0.2rem;
  font-size: 0.95rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.conv-preview {
  font-size: 0.85rem;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

.chat-container.dark .conv-preview {
  color: #bbb;
}

.conv-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 0.3rem;
  font-size: 0.75rem;
  color: #999;
}

.conv-unread {
  color: #007bff;
  font-size: 0.8rem;
}

.delete-conv {
  position: absolute;
  top: 5px;
  right: 5px;
  background: transparent;
  border: none;
  color: #999;
  cursor: pointer;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  opacity: 0;
  transition: all 0.2s;
}

.conv-item:hover .delete-conv {
  opacity: 1;
}

.delete-conv:hover {
  background: rgba(220, 53, 69, 0.1);
  color: #dc3545;
}

/* 聊天区域增强 */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 1rem;
  width: 100%;
  margin-left: 0;
  transition: margin-left 0.3s ease;
}

.conversations-sidebar.active + .chat-area {
  margin-left: 280px;
}

/* 角色选择区增强 */
.role-section {
  margin-bottom: 1rem;
  display: flex;
  align-items: center;
  gap: 1rem;
  flex-wrap: wrap;
  padding: 0.5rem 0;
}

.role-select {
  padding: 0.5rem 1rem;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 1rem;
  background: white;
  cursor: pointer;
  transition: border-color 0.2s, box-shadow 0.2s;
}

.chat-container.dark .role-select {
  background: #333;
  border-color: #444;
  color: #fff;
}

.role-select:focus {
  border-color: #007bff;
  box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
  outline: none;
}

.chat-actions {
  margin-left: auto;
  display: flex;
  gap: 0.5rem;
}

.action-btn {
  background: transparent;
  border: 1px solid #e1e5e9;
  border-radius: 8px;
  padding: 0.5rem 0.8rem;
  cursor: pointer;
  font-size: 0.9rem;
  color: #666;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 0.3rem;
}

.chat-container.dark .action-btn {
  border-color: #444;
  color: #bbb;
}

.action-btn:hover:not(:disabled) {
  background: #f1f1f1;
  color: #333;
}

.chat-container.dark .action-btn:hover:not(:disabled) {
  background: #444;
  color: #fff;
}

.action-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.clear-btn {
  color: #dc3545;
  border-color: #f5c6cb;
}

.chat-container.dark .clear-btn {
  color: #ff6b6b;
  border-color: #573a3a;
}

.clear-btn:hover:not(:disabled) {
  background: #f8d7da;
  color: #721c24;
}

.chat-container.dark .clear-btn:hover:not(:disabled) {
  background: #573a3a;
  color: #ff6b6b;
}

/* 消息容器增强 */
.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 1.5rem;
  border: 1px solid #e1e5e9;
  border-radius: 12px;
  margin-bottom: 1rem;
  background: white;
  scroll-behavior: smooth;
  scrollbar-width: thin;
  scrollbar-color: #ccc transparent;
}

.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 3px;
}

.chat-container.dark .messages-container {
  background: #2d2d2d;
  border-color: #444;
  scrollbar-color: #555 transparent;
}

.chat-container.dark .messages-container::-webkit-scrollbar-thumb {
  background-color: #555;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
  padding: 2rem;
  text-align: center;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
  opacity: 0.5;
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-10px); }
}

.role-desc {
  margin-top: 0.5rem;
  font-size: 0.9rem;
  max-width: 80%;
  line-height: 1.5;
  color: #666;
}

.chat-container.dark .role-desc {
  color: #aaa;
}

/* 消息样式增强 */
.message {
  display: flex;
  margin-bottom: 1.2rem;
  gap: 0.75rem;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.message.user {
  flex-direction: row-reverse;
}

.message-avatar {
  font-size: 1.5rem;
  display: flex;
  align-items: flex-start;
  min-width: 36px;
  height: 36px;
  justify-content: center;
  margin-top: 0.2rem;
}

.message-content {
  max-width: 75%;
  padding: 0.8rem 1rem;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  position: relative;
  transition: transform 0.1s;
}

.message-content:hover {
  transform: translateY(-1px);
}

.message:not(.user) .message-content {
  background: white;
  border: 1px solid #eee;
  border-top-left-radius: 4px;
}

.chat-container.dark .message:not(.user) .message-content {
  background: #3a3a3a;
  border-color: #444;
}

.message.user .message-content {
  background: #007bff;
  color: white;
  border-top-right-radius: 4px;
}

.message-sender {
  font-weight: bold;
  font-size: 0.875rem;
  margin-bottom: 0.3rem;
  color: #666;
}

.chat-container.dark .message-sender {
  color: #ccc;
}

.message.user .message-sender {
  color: rgba(255, 255, 255, 0.9);
}

.message-text {
  line-height: 1.5;
  margin-bottom: 0.5rem;
  white-space: pre-wrap;
  word-break: break-word;
}

.message-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.message-time {
  font-size: 0.75rem;
  opacity: 0.7;
}

.message-actions {
  display: flex;
  gap: 0.5rem;
}

.copy-btn, .delete-btn {
  background: transparent;
  border: none;
  font-size: 0.75rem;
  cursor: pointer;
  opacity: 0.7;
  padding: 0.2rem 0.4rem;
  border-radius: 4px;
  transition: all 0.2s;
  color: inherit;
}

.copy-btn:hover, .delete-btn:hover {
  opacity: 1;
  background: rgba(0, 0, 0, 0.05);
}

.message.user .copy-btn:hover, .message.user .delete-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.delete-btn {
  color: #dc3545;
}

/* 加载状态与重试区域 */
.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 1rem;
  gap: 0.5rem;
  animation: fadeIn 0.3s ease;
}

.retry-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 1rem;
  gap: 0.8rem;
  color: #dc3545;
  animation: fadeIn 0.3s ease;
}

.retry-btn {
  background: #dc3545;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 0.4rem 1rem;
  cursor: pointer;
  transition: background 0.2s;
  font-size: 0.9rem;
}

.retry-btn:hover {
  background: #c82333;
}

.typing-dots {
  display: flex;
  gap: 0.35rem;
}

.typing-dots span {
  height: 10px;
  width: 10px;
  background: #007bff;
  border-radius: 50%;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-text {
  font-size: 0.9rem;
  color: #666;
}

.chat-container.dark .typing-text {
  color: #bbb;
}

.typing-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% { transform: scale(0.8); }
  40% { transform: scale(1.2); }
}

/* 输入区域增强 */
.input-section {
  border-top: 1px solid #e1e5e9;
  padding-top: 1rem;
  position: relative;
}

.chat-container.dark .input-section {
  border-top-color: #444;
}

.input-toolbar {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 0.5rem;
  padding-left: 0.25rem;
  align-items: center;
}

.toolbar-btn {
  background: transparent;
  border: none;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background 0.2s, transform 0.1s;
  font-size: 1rem;
  position: relative;
}

.toolbar-btn:hover {
  background: #f1f1f1;
  transform: scale(1.05);
}

.chat-container.dark .toolbar-btn:hover {
  background: #444;
}

/* 输入字数统计 */
.input-counter {
  margin-left: auto;
  font-size: 0.8rem;
  color: #999;
}

.input-counter.warning {
  color: #ffc107;
}

.input-counter.error {
  color: #dc3545;
}

/* 表情选择器 */
.emoji-picker {
  position: absolute;
  bottom: 100%;
  left: 0;
  background: white;
  border-radius: 8px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  padding: 0.8rem;
  margin-bottom: 0.5rem;
  z-index: 5;
  width: 280px;
}

.chat-container.dark .emoji-picker {
  background: #333;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.3);
}

.emoji-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 0.5rem;
}

.emoji-grid span {
  font-size: 1.2rem;
  text-align: center;
  padding: 0.3rem;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.2s;
}

.emoji-grid span:hover {
  background: #f1f1f1;
}

.chat-container.dark .emoji-grid span:hover {
  background: #444;
}

.input-group {
  display: flex;
  gap: 0.75rem;
}

.message-input {
  flex: 1;
  padding: 0.85rem 1rem;
  border: 2px solid #e1e5e9;
  border-radius: 12px;
  font-size: 1rem;
  outline: none;
  resize: none;
  overflow: hidden;
  transition: border-color 0.2s, box-shadow 0.2s;
  background: white;
  line-height: 1.5;
}

.message-input:disabled {
  background: #f8f9fa;
  cursor: not-allowed;
}

.chat-container.dark .message-input {
  background: #333;
  border-color: #444;
  color: #fff;
}

.chat-container.dark .message-input:disabled {
  background: #444;
}

.message-input:focus {
  border-color: #007bff;
  box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
}

/* 输入框达到最大长度时的样式 */
.message-input.limit-reached {
  border-color: #dc3545;
  box-shadow: 0 0 0 3px rgba(220, 53, 69, 0.1);
}

.send-btn {
  padding: 0.75rem 1.5rem;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  font-size: 1rem;
  font-weight: 500;
  transition: background 0.2s, transform 0.1s;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 100px;
}

.send-btn:not(:disabled):hover {
  background: #0056b3;
}

.send-btn:not(:disabled):active {
  transform: scale(0.98);
}

.send-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
  transform: none;
}

/* 底部状态栏增强 */
.chat-footer {
  padding: 0.75rem 1.5rem;
  background: white;
  border-top: 1px solid #e1e5e9;
  font-size: 0.875rem;
}

.chat-container.dark .chat-footer {
  background: #2d2d2d;
  border-top-color: #444;
}

.status {
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.status-icon {
  font-size: 1rem;
}

.status.success {
  color: #28a745;
}

.status.error {
  color: #dc3545;
}

.status.info {
  color: #17a2b8;
}

.retry-link {
  color: inherit;
  text-decoration: underline;
  background: none;
  border: none;
  cursor: pointer;
  padding: 0;
  font-size: inherit;
}

.retry-link:hover {
  opacity: 0.8;
}

/* 通知提示增强 */
.notification {
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding: 0.8rem 1.2rem;
  border-radius: 8px;
  background: #333;
  color: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(100px);
  opacity: 0;
  transition: all 0.3s ease;
  z-index: 100;
  font-size: 0.9rem;
  cursor: pointer;
  max-width: 300px;
}

.notification.show {
  transform: translateY(0);
  opacity: 1;
  animation: slideIn 0.3s ease;
}

@keyframes slideIn {
  from { transform: translateY(100px); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}

.notification.success {
  background: #28a745;
}

.notification.error {
  background: #dc3545;
}

/* 响应式设计增强 */
@media (max-width: 768px) {
  .chat-header {
    padding: 0.75rem 1rem;
  }

  .chat-header h1 {
    font-size: 1.25rem;
  }

  .conversations-sidebar {
    width: 100%;
    height: calc(100vh - 56px - 42px);
    z-index: 100;
  }

  .conversations-sidebar.active + .chat-area {
    margin-left: 0;
  }

  .message-content {
    max-width: 85%;
  }

  .role-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }

  .chat-actions {
    margin-left: 0;
    align-self: flex-end;
    width: 100%;
    justify-content: flex-end;
  }

  .messages-container {
    padding: 1rem 0.5rem;
    max-height: 50vh;
  }

  .send-btn {
    min-width: 80px;
    padding: 0.75rem;
  }

  .emoji-picker {
    width: calc(100% - 1rem);
  }
}
</style>